import json
import unittest
from multiprocessing.pool import ThreadPool

import requests
from tqdm import tqdm

from Spider.close20 import get_last20mean


def change_fund_flag_to_error(fund):
    res = requests.patch("http://127.0.0.1:8000/index/api/fund/{}/".format(fund['f_id']),
                         data={"f_flag": -1})

    print(res)


class MyTestCase(unittest.TestCase):

    def test_update_stack(self):
        res = requests.patch("http://127.0.0.1:8000/index/api/stack/601898/",
                             data={"s_flag_refresh": 1})
        print(res)

    def test_update_fund(self):
        res = requests.patch("http://127.0.0.1:8000/index/api/fund/160105/",
                             data={"f_flag_refresh": 1})
        print(res)

    def test_get_last20mean(self):
        acode = "600806"
        hcode = "0300.hk"
        s_mean20 = get_last20mean({'s_acode': acode, 's_hcode': hcode})
        print(s_mean20)

    def test_update_stack_close20(self):
        """
        测试更新前20天平均值

        :return:
        """
        acode = "601991"
        hcode = "0991.hk"
        s_mean20 = get_last20mean(acode, hcode)

        res = requests.patch("http://127.0.0.1:8000/index/api/stack/601991/",
                             data={"s_20mean": s_mean20})
        print(res)

    def test_get_stacks(self):
        stacks = requests.get("http://127.0.0.1:8000/index/api/stack/?format=json").text
        stacks = json.loads(stacks)
        for stack in tqdm(stacks):
            acode = stack["s_acode"]
            hcode = stack["s_hcode"]
            s_mean20, info = get_last20mean(acode, hcode)
            res = requests.patch("http://127.0.0.1:8000/index/api/stack/{}/".format(acode),
                                 data={"s_20mean": s_mean20})
            print(res)

    def test_change_flags(self):
        """
        修改基金所有状态为异常
        :return:
        """
        funds = requests.get("http://127.0.0.1:8000/index/api/fund/?format=json").text
        funds = json.loads(funds)
        task_pool = ThreadPool(100)
        task_pool.map(change_fund_flag_to_error, funds)
        task_pool.close()
        task_pool.join()

    def test_change_convfond_flags(self):
        funds = requests.get("http://127.0.0.1:8000/index/api/conv_bond/?format=json").text
        funds = json.loads(funds)
        task_pool = ThreadPool(100)
        task_pool.map(change_fund_flag_to_error, funds)
        task_pool.close()
        task_pool.join()

    def test_easyquotation(self):
        import easyquotation
        quot = easyquotation.use('tencent')
        a = quot.market_snapshot(prefix=True)
        a_162411 = quot.real('161005')
        print()

    def test_tushare(self):
        import tushare as ts
        while True:
            re = ts.get_realtime_quotes(['600848', '000981'])
            print(re)

if __name__ == '__main__':
    unittest.main()
